<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="parName">
        <el-input
            v-model="queryParams.parName"
            placeholder="请输入名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="contStartTime">
        <el-date-picker clearable
                        v-model="queryParams.contStartTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="contEndTime">
        <el-date-picker clearable
                        v-model="queryParams.contEndTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="联系人" prop="contactName">
        <el-input
            v-model="queryParams.contactName"
            placeholder="请输入联系人"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系方式" prop="contactWay">
        <el-input
            v-model="queryParams.contactWay"
            placeholder="请输入联系方式"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
              v-for="dict in t_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
              v-show="dict.value !== '02' && dict.value !== '00' && dict.value !== '01' && dict.value !== '03'"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="城市" prop="cityCode">
        <el-cascader-area v-model="queryParams.cityCode" :qrtType="1"></el-cascader-area>
      </el-form-item>
      <el-form-item label="编码" prop="parCode">
        <el-input
            v-model="queryParams.parCode"
            placeholder="请输入编码"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:tpar:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:tpar:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:tpar:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tparList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="编码" align="center" prop="parCode"/>
      <el-table-column label="名称" align="center" prop="parName"/>
      <el-table-column label="城市" align="center" prop="cityName"/>
      <el-table-column label="签约时间" align="center" prop="contSignTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.contSignTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合约期限" align="center" prop="contLimit"/>
      <el-table-column label="合约时间" align="center" prop="saleStartTime" width="190">
        <template #default="scope">
          <span>{{
              parseTime(scope.row.contStartTime, '{y}-{m}-{d}')
            }}至{{ parseTime(scope.row.contEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="联系人" align="center" prop="contactName"/>
      <el-table-column label="联系方式" align="center" prop="contactWay"/>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="t_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="280" class-name="small-padding fixed-width" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     :class="{'but-disabled': scope.row.status === '04'}"
                     v-hasPermi="['system:tpar:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     :class="{'but-disabled': scope.row.status === '04'}"
                     v-hasPermi="['system:tpar:remove']">删除
          </el-button>
          <el-button link type="primary" icon="User" @click="handleMerUser(scope.row)"
                     :class="{'but-disabled': scope.row.status === '04'}"
                     v-hasPermi="['system:tpar:user']">账号
          </el-button>
          <!--          <el-button link type="primary" icon="OfficeBuilding" @click="handleCityUser(scope.row)"-->
          <!--                     :class="{'but-disabled': scope.row.status === '04'}"-->
          <!--                     v-hasPermi="['system:tpar:city']">城市-->
          <!--          </el-button>-->
          <el-button link type="primary" icon="CloseBold" @click="handleTerminate(scope.row)"
                     :class="{'but-disabled': !(scope.row.status === '02' || scope.row.status === '10' || scope.row.status === '11')}"
                     v-hasPermi="['system:tpar:terminate']">终止
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改经销商列表对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="tparRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="名称" prop="parName">
              <el-input v-model="form.parName" placeholder="请输入经销商名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="签约时间" prop="contSignTime">
              <el-date-picker clearable
                              v-model="form.contSignTime"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择签约时间"
                              @change="handleSignTime"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <!-- <el-tooltip content="Top center" placement="top-start"> -->
            <el-form-item label="签约起止" prop="contStartTime">
              <el-date-picker
                  clearable
                  v-model="contTimeRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                  @change="handleContTimeChange"
              ></el-date-picker>
            </el-form-item>
            <!-- </el-tooltip> -->
          </el-col>
          <el-col :span="12">
            <el-form-item label="合约期限" prop="contLimit">
              <el-input v-model="form.contLimit" placeholder="请输入合约期限" :readonly="true"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactName">
              <el-input v-model="form.contactName" placeholder="请输入联系人"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="contactWay">
              <el-input v-model="form.contactWay" placeholder="请输入联系方式"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="合同信息" prop="contPic">
              <image-upload v-model="form.contPic" :limit="9"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="地区" prop="areaCode">
              <el-cascader-area v-model="form.areaCode" :qrtType="2"></el-cascader-area>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详细地址" prop="addr">
              <el-input v-model="form.addr" type="textarea" placeholder="请输入详细地址"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <map-component :key="mapComponentKey"
                           :longitude="form.longitude" :latitude="form.latitude"
                           @coordinateClicked="handleCoordinateClicked"
            ></map-component>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="描述" prop="parDesc">
              <el-input v-model="form.parDesc" placeholder="请输入经销商描述"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Tpar">
import {listTpar, getTpar, delTpar, addTpar, updateTpar, updateStatus} from "@/api/system/tpar";
import {ref} from "vue";
import router from "@/router";
import {ElMessage} from 'element-plus'
import {getAreaCode} from "@/api/system/sysCity";

const {proxy} = getCurrentInstance();
const {t_status} = proxy.useDict('t_status');

const tparList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const contTimeRange = ref([]);
const mapComponentKey = ref(0);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    parName: undefined,
    parDesc: undefined,
    type: undefined,
    contSignTime: undefined,
    contStartTime: undefined,
    contEndTime: undefined,
    contLimit: undefined,
    contactName: undefined,
    contactWay: undefined,
    cityCode: undefined,
    areaCode: undefined,
    areaPath: undefined,
    addr: undefined,
    addrDesc: undefined,
    longitude: undefined,
    latitude: undefined,
    status: undefined,
  },
  rules: {
    parName: [
      {required: true, message: "经销商名称不能为空", trigger: "blur"}
    ],
    contSignTime: [
      {required: true, message: "请选择签约时间！", trigger: "change"},
    ],
    contStartTime: [
      {required: true, message: "请选择签约起止时间！", trigger: "change"},
    ],
    contactName: [
      {required: true, message: "联系人不能为空", trigger: "change"}
    ],
    contactWay: [
      {required: true, message: "联系方式不能为空", trigger: "change"},
      {
        validator: (rule, value, callback) => {
          const reg = /^[1][3-9]\d{9}$/;
          if (reg.test(value)) {
            callback();
          } else {
            callback(new Error("请输入有效的手机号"));
          }
        },
        trigger: "blur"
      }
    ],
    areaCode: [
      {required: true, message: "地区不能为空！", trigger: "blur"},
    ],
    addr: [
      {required: true, message: "详细地址不能为空！", trigger: "blur"},
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询经销商列表列表 */
function getList() {
  loading.value = true;
  listTpar(queryParams.value).then(response => {
    tparList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    parId: undefined,
    parCode: undefined,
    parName: undefined,
    parDesc: undefined,
    type: undefined,
    contSignTime: undefined,
    contStartTime: undefined,
    contEndTime: undefined,
    contLimit: undefined,
    contactName: undefined,
    contactWay: undefined,
    cityCode: undefined,
    areaCode: undefined,
    areaPath: undefined,
    addr: undefined,
    addrDesc: undefined,
    longitude: 118.8083,
    latitude: 31.8639,
    status: undefined,
    statusReason: undefined,
    auditTime: undefined,
    auditor: undefined,
    ext1: undefined,
    ext2: undefined,
    ext3: undefined,
    state: undefined,
    createTime: undefined,
    creator: undefined,
    modifyTime: undefined,
    modifier: undefined
  };
  proxy.resetForm("tparRef");
  contTimeRange.value = [];
  mapComponentKey.value += 1;
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  // ids.value = selection.map(item => item.parId);
  // single.value = selection.length != 1;
  // multiple.value = !selection.length;
  ids.value = selection.map(item => item.parId);
  single.value = selection.length != 1;
  // multiple.value = !selection.length;
  let type = true
  if (selection.length == 1) {
    // 只选择一个

    if (selection[0].status !== '04') {
      type = false
    } else {
      type = true
    }
  } else {
    // 选择多个
    type = false
    if (selection.length == 0) {
      type = true
    } else {
      selection.map(item => {
        if (item.status == '04') {
          type = true
          return
        }
      })
    }

  }
  multiple.value = type
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加经销商";
  mapComponentKey.value += 1;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _parId = row.parId || ids.value
  getTpar(_parId).then(response => {
    form.value = response.data;
    contTimeRange.value = [response.data.contStartTime, response.data.contEndTime];
    open.value = true;
    title.value = "修改经销商";
    mapComponentKey.value += 1;
  });
}

/** 提交按钮 */
function submitForm() {
  if (form.value.contSignTime > form.value.contStartTime) {
    ElMessage.error('签约时间不能大于签约起止中的开始时间哦！')
    return
  }
  proxy.$refs["tparRef"].validate(valid => {
    if (valid) {
      if (form.value.parId != null) {
        updateTpar(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTpar(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 账号按钮操作 */
function handleMerUser(row) {
  router.push('/system/tparuser/index/' + row.parId)
}

/** 城市按钮操作 */
function handleCityUser(row) {
  router.push('/system/tpararea/index/' + row.parId)
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _parIds = row.parId || ids.value;
  proxy.$modal.confirm('是否确认删除经销商编号为"' + _parIds + '"的数据项？').then(function () {
    return delTpar(_parIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

function handleTerminate(row) {
  const _parIds = row.parId || ids.value;
  proxy.$modal.confirm('是否确认终止经销商，编号为"' + _parIds + '"的数据项？').then(function () {
    row.status = "04";
    return updateStatus(row);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("终止成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/tpar/export', {
    ...queryParams.value
  }, `tpar_${new Date().getTime()}.xlsx`)
}

function handleSignTime() {
  if (form.value.contSignTime > form.value.contStartTime) {
    ElMessage.error('签约时间不能大于签约起止中的开始时间哦！')
  }
}

function handleContTimeChange(value) {
  if (value[0] < form.value.contSignTime) {
    ElMessage.error('签约起止中的开始时间不能小于签约时间哦！')
  }
  if (value && value.length === 2) {
    form.value.contStartTime = value[0];
    form.value.contEndTime = value[1];

    const startDate = new Date(value[0]);
    const endDate = new Date(value[1]);

    const MS_PER_MONTH = 1000 * 60 * 60 * 24 * 30;

    const timeDifference = endDate - startDate;
    const monthsDifference = timeDifference / MS_PER_MONTH;

    // if (monthsDifference >= 12) {
    //   const years = Math.floor(monthsDifference / 12);
    //   const remainingMonths = Math.floor(monthsDifference % 12);
    //
    //   if (remainingMonths > 0) {
    //     form.value.contractYears = `${years}年${remainingMonths}个月`;
    //   } else {
    //     form.value.contractYears = `${years}年`;
    //   }
    // } else {
    form.value.contLimit = `${Math.floor(monthsDifference)}个月`;
    // }
  }
}

function handleCoordinateClicked(coordinate) {
  // 更新经纬度
  form.value.longitude = coordinate.lng;
  form.value.latitude = coordinate.lat;
  form.value.addr = coordinate.addr;
  getAreaCode({
    provinceExtName: coordinate.province,
    cityExtName: coordinate.city,
    districtExtName: coordinate.district,
    isOpenCity: 0
  }).then(response => {
    form.value.areaCode = response.data.district;
  });
}

getList();
</script>
